<template>
  <div id="viewFile" style="height:100%"></div>
</template>
<script>
export default {
  props: ['wpsUrl', 'token'],
  data() {
    return {
      // 是否开启简易模式
      simpleMode: false,
      jssdk: '',
      selectText: 'moren'
    }
  },
  watch:{
    selectText(val){
      this.$bus.$emit("receiveSelectionText",val)
    }
  },
  mounted() {
    this.openWps(this.wpsUrl, this.token);
  },
  methods: {
    async openWps(url, token) {
      let _this = this;
      const wps = _this.wps.config({
        mode: _this.simpleMode ? 'simple' : 'normal',
        mount: document.querySelector('#viewFile'),
        wpsUrl: url,
      });
      wps.setToken({token});
      await wps.ready();
      let app = wps.Application;
      this.jssdk = wps;

      //excel 选中区域监听
      wps.ApiEvent.AddApiEventListener("Worksheet_SelectionChange", (data) => {
        const select = excelSelectionChangeHandle(wps);
        select.then((data) => {
          this.selectText = data
        })
      });

      //word 选中区域监听
      wps.ApiEvent.AddApiEventListener("WindowSelectionChange", (data) => {
        const text = wordSelectionChangeHandle(wps, data.begin, data.end)
        text.then((data) => {
          this.selectText = data
        })
        console.log("this.selectText", this.selectText)
      });
      //PPT 不存在选中监听事件
      //pdf 选区监听，但无法获取选区内容
      // wps.ApiEvent.AddApiEventListener("TextSelectChange", (data) => {
      //   console.log("pdf-selection", data)
      // });

      async function wordSelectionChangeHandle(jssdk, begin, end) {
        // 选区对象
        const range = await jssdk.Application.ActiveDocument.Range(begin, end);
        const text = await range.Text;
        // console.log("range",text);
        return text;
      }


      async function excelSelectionChangeHandle(jssdk) {
        // const app = this.instance.Application;
        const selection = await jssdk.Application.Selection
        const Row = await selection.Row
        const RowEnd = await selection.RowEnd
        const Column = await selection.Column
        const ColumnEnd = await selection.ColumnEnd
        let selects = '';
        for (let i = Row; i <= RowEnd; i++) {
          for (let j = Column; j <= ColumnEnd; j++) {
            const columnCode = await jssdk.Application.Base10To26(j) // 列号转字母
            const text = await jssdk.Application.Range(columnCode + i).Text
            selects = selects + text
          }
        }
        return selects;
      }
    }
  }
}
</script>
